'use strict';

const db = uniCloud.database();

module.exports = {
  _before: function () {
    // 获取客户端信息
    this.clientInfo = this.getClientInfo();
    console.log('match-schedule-object _before 初始化完成');
    
    // 【新增】异步初始化操作日志表（不阻塞主流程）
    module.exports.initOperationLogsTable().catch(error => {
      console.error('初始化操作日志表失败:', error);
    });
  },

  /**
   * 获取比赛日程（修复方法名匹配问题）
   */
  async getMatchSchedule(matchId) {
    if (!matchId) {
      return {
        code: -1,
        message: '比赛ID不能为空'
      };
    }
    
    try {
      const result = await db.collection('match_schedules')
        .where({ match_id: matchId })
        .orderBy('date', 'asc')
        .get();
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: result.data
        }
      };
      
    } catch (error) {
      console.error('获取比赛日程失败:', error);
      return {
        code: -1,
        message: '获取日程失败'
      };
    }
  },

  /**
   * 获取比赛日程列表（保持原有方法兼容性）
   */
  async getSchedules(params) {
    const { matchId } = params;
    if (!matchId) {
      return {
        code: -1,
        message: '比赛ID不能为空'
      };
    }
    
    try {
      const result = await db.collection('match_schedules')
        .where({ match_id: matchId })
        .orderBy('date', 'asc')
        .get();
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: result.data
        }
      };
      
    } catch (error) {
      console.error('获取比赛日程失败:', error);
      return {
        code: -1,
        message: '获取日程失败'
      };
    }
  },

  /**
   * 获取比赛日程列表（前端调用的方法名）
   */
  async getMatchSchedules(matchId) {
    if (!matchId) {
      return {
        code: -1,
        message: '比赛ID不能为空'
      };
    }
    
    try {
      const result = await db.collection('match_schedules')
        .where({ match_id: matchId })
        .orderBy('date', 'asc')
        .get();
      
      // 为每个日程获取完整的时段和申请记录信息
      const scheduleList = await Promise.all(result.data.map(async (schedule) => {
        if (schedule.time_slots && Array.isArray(schedule.time_slots)) {
          // 为每个时段获取申请记录
          const timeSlotsWithApplications = await Promise.all(schedule.time_slots.map(async (slot) => {
            try {
              // 从数据库获取该时段的申请记录
              const applicationsResult = await db.collection('match_applications')
                .where({
                  schedule_id: schedule._id,
                  slot_id: slot.slot_id
                })
                .get();
              
              return {
                ...slot,
                applications: applicationsResult.data || []
              };
            } catch (error) {
              console.error(`获取时段 ${slot.slot_id} 的申请记录失败:`, error);
              return {
                ...slot,
                applications: []
              };
            }
          }));
          
          return {
            ...schedule,
            time_slots: timeSlotsWithApplications
          };
        }
        
        return schedule;
      }));
      
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: scheduleList
        }
      };
      
    } catch (error) {
      console.error('获取比赛日程失败:', error);
      return {
        code: -1,
        message: '获取日程失败'
      };
    }
  },

  /**
   * 获取单个日程详情
   */
  async getScheduleDetail(scheduleId) {
    if (!scheduleId) {
      return {
        code: -1,
        message: '日程ID不能为空'
      };
    }
    
    try {
      const result = await db.collection('match_schedules')
        .doc(scheduleId)
        .get();
      
      if (!result.data.length) {
        return {
          code: -1,
          message: '日程不存在'
        };
      }
      
      return {
        code: 0,
        message: '获取成功',
        data: result.data[0]
      };
      
    } catch (error) {
      console.error('获取日程详情失败:', error);
      return {
        code: -1,
        message: '获取日程详情失败'
      };
    }
  },

  /**
   * 保存比赛日程
   */
  async saveMatchSchedules(params) {
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { matchId, schedules } = params;

      if (!matchId || !schedules || !Array.isArray(schedules)) {
        return {
          code: -1,
          message: '参数错误'
        };
      }

      // 验证用户是否是比赛组织者
      const matchResult = await db.collection('matches').doc(matchId).get();
      
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '只有比赛发布者才能创建日程'
        };
      }

      // 删除现有日程
      await db.collection('match_schedules').where({
        match_id: matchId
      }).remove();

      // 添加新日程
      const now = new Date();
      const schedulePromises = schedules.map(schedule => {
        return db.collection('match_schedules').add({
          match_id: matchId,
          date: schedule.date,
          start_time: schedule.start_time,
          end_time: schedule.end_time,
          event_name: schedule.event_name,
          venue: schedule.venue,
          referee_requirements: schedule.referee_requirements || [],
          notes: schedule.notes || '',
          organizer_id: userId,
          create_time: now,
          update_time: now
        });
      });

      await Promise.all(schedulePromises);

      // 发送批量日程保存通知给全平台用户
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        // 获取全平台用户
        const userCollection = db.collection('users');
        const usersResult = await userCollection.field({
          _id: true
        }).get();
        
        if (usersResult.data && usersResult.data.length > 0) {
          const userIds = usersResult.data.map(user => user._id);
          
          // 构建批量日程通知内容
          const scheduleCount = schedules.length;
          const dateRange = schedules.length > 0 ? 
            (schedules.length === 1 ? schedules[0].date : 
             `${schedules[0].date} 至 ${schedules[schedules.length - 1].date}`) : 
            '日期待定';
          
          await notificationService.batchSendNotification({
            userIds: userIds,
            type: 'match_publish',
            title: `系列赛日程发布：${match.title}`,
            content: `${match.title} 的系列赛日程已发布！比赛日期：${dateRange}，共${scheduleCount}个比赛日。完整赛程安排已公布，敬请关注！`,
            relatedId: matchId,
            senderId: userId,
            extraData: {
              jump_type: 'match_detail',
              jump_url: `/packgeCompetition/competition/detail?id=${matchId}`,
              match_id: matchId,
              schedule_count: scheduleCount,
              date_range: dateRange,
              match_title: match.title
            }
          });
          
          console.log(`系列赛日程保存通知已发送给全平台 ${userIds.length} 名用户`);
        }
      } catch (notifyError) {
        console.error('发送系列赛日程保存通知失败:', notifyError);
        // 不影响日程保存的主流程
      }

      return {
        code: 0,
        message: '保存成功'
      };
      
    } catch (error) {
      console.error('保存比赛日程失败:', error);
      return {
        code: -1,
        message: '保存日程失败'
      };
    }
  },

  /**
   * 创建比赛日程
   */
  async createSchedule(params) {
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
      return {
          code: -1,
          message: '未登录或登录状态已过期'
      };
    }
    
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      const { matchId, scheduleData } = params;
      
      if (!matchId || !scheduleData) {
        return {
          code: -1,
          message: '缺少必要参数'
        };
      }
      
      // 验证用户是否是比赛组织者
      const matchResult = await db.collection('matches').doc(matchId).get();
      
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '只有比赛发布者才能创建日程'
        };
      }
      
      // 数据验证
      const { date, venue, time_slots } = scheduleData;
      
      if (!date || !venue || !time_slots || time_slots.length === 0) {
        return {
          code: -1,
          message: '请填写完整的日程信息'
        };
      }
      
      // 验证时段数据
      for (let i = 0; i < time_slots.length; i++) {
        const slot = time_slots[i];
        if (!slot.start_time || !slot.end_time) {
          return {
            code: -1,
            message: `第${i + 1}个时段信息不完整`
          };
        }
        
        if (slot.start_time >= slot.end_time) {
          return {
            code: -1,
            message: `第${i + 1}个时段的结束时间必须晚于开始时间`
          };
        }
      }
      
      // 检查是否存在重复的日程
      const existingSchedule = await db.collection('match_schedules').where({
        match_id: matchId,
        date: date
      }).get();
      
      if (existingSchedule.data.length > 0) {
        return {
          code: -1,
          message: '该日期已存在比赛日程安排'
        };
      }
      
      // 处理时段数据
      const processedTimeSlots = time_slots.map(slot => ({
        slot_id: slot.id || Date.now().toString() + Math.random().toString(36).substr(2, 5),
        start_time: slot.start_time,
        end_time: slot.end_time,
        venue: slot.venue || venue,
        referee_requirements: slot.referee_requirements || {},
        status: 'open'
      }));
      
      // 创建新的日程
      const newSchedule = {
        match_id: matchId,
        date: date,
        venue: venue,
        time_slots: processedTimeSlots,
        status: 'open',
        organizer_id: userId,
        create_time: new Date(),
        update_time: new Date()
      };
      
      const result = await db.collection('match_schedules').add(newSchedule);
      
      // 发送比赛日程创建通知给全平台用户
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        // 获取全平台用户
        const userCollection = db.collection('users');
        const usersResult = await userCollection.field({
          _id: true
        }).get();
        
        if (usersResult.data && usersResult.data.length > 0) {
          const userIds = usersResult.data.map(user => user._id);
          
          // 构建日程通知内容
          const slotCount = time_slots.length;
          const timeRange = time_slots.length > 0 ? 
            `${time_slots[0].start_time}-${time_slots[time_slots.length - 1].end_time}` : 
            '时间待定';
          
          await notificationService.batchSendNotification({
            userIds: userIds,
            type: 'match_publish',
            title: `新比赛日程发布：${match.title}`,
            content: `${match.title} 的比赛日程已发布！日期：${date}，地点：${venue}，时段：${timeRange}，共${slotCount}个时段。快来申请执裁吧！`,
            relatedId: matchId,
            senderId: userId,
            extraData: {
              jump_type: 'match_detail',
              jump_url: `/packgeCompetition/competition/detail?id=${matchId}`,
              match_id: matchId,
              schedule_id: result.id,
              match_date: date,
              venue: venue
            }
          });
          
          console.log(`比赛日程创建通知已发送给全平台 ${userIds.length} 名用户`);
        }
      } catch (notifyError) {
        console.error('发送比赛日程创建通知失败:', notifyError);
        // 不影响日程创建的主流程
      }
      
      return {
        code: 0,
        message: '日程创建成功',
        data: {
          _id: result.id,
          ...newSchedule
        }
      };
      
    } catch (error) {
      console.error('创建比赛日程失败:', error);
      return {
        code: -1,
        message: '创建日程失败'
      };
    }
  },

  /**
   * 更新比赛日程
   */
  async updateSchedule(scheduleId, updateData) {
    if (!scheduleId) {
      return {
        code: -1,
        message: '日程ID不能为空'
      };
    }
    
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }
      
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      
      // 检查日程是否存在且有权限修改
      const scheduleResult = await db.collection('match_schedules').doc(scheduleId).get();
      
      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '日程不存在'
        };
      }
      
      const schedule = scheduleResult.data[0];
      
      if (schedule.organizer_id !== userId) {
        return {
          code: -1,
          message: '无权限修改此日程'
        };
      }
      
      // 更新数据
      const finalUpdateData = {
        ...updateData,
        update_time: new Date()
      };
      
      // 移除不应该更新的字段
      delete finalUpdateData._id;
      delete finalUpdateData.match_id;
      delete finalUpdateData.organizer_id;
      delete finalUpdateData.create_time;
      
      const result = await db.collection('match_schedules').doc(scheduleId).update(finalUpdateData);
      
      return {
        code: 0,
        message: '更新成功',
        data: result
      };
      
    } catch (error) {
      console.error('更新比赛日程失败:', error);
      return {
        code: -1,
        message: '更新日程失败'
      };
    }
  },

  /**
   * 删除比赛日程
   */
  async deleteSchedule(scheduleId) {
    if (!scheduleId) {
      return {
        code: -1,
        message: '日程ID不能为空'
      };
    }
    
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }
      
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      
      // 检查日程是否存在且有权限删除
      const scheduleResult = await db.collection('match_schedules').doc(scheduleId).get();
      
      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '日程不存在'
        };
      }
      
      const schedule = scheduleResult.data[0];
      
      if (schedule.organizer_id !== userId) {
        return {
          code: -1,
          message: '无权限删除此日程'
        };
      }
      
      const result = await db.collection('match_schedules').doc(scheduleId).remove();
      
      return {
        code: 0,
        message: '删除成功',
        data: result
      };
      
    } catch (error) {
      console.error('删除比赛日程失败:', error);
      return {
        code: -1,
        message: '删除日程失败'
      };
    }
  },

  /**
   * 创建多时段比赛日程（新版本功能）
   */
  async createMultiSlotSchedule(scheduleData) {
    try {
      console.log('开始创建多时段比赛日程:', scheduleData)
      
      // 获取token
      const token = this.getUniIdToken()
      if (!token) {
        return { code: 401, message: '未登录或登录状态已过期' }
      }
      
      // 使用user-service验证token
      const userService = uniCloud.importObject('user-service')
      const tokenResult = await userService.verifyToken({ token })
      
      if (tokenResult.code !== 0) {
        console.error('Token验证失败:', tokenResult)
        return { code: 401, message: tokenResult.message || 'Token验证失败' }
      }
      
      const userId = tokenResult.data.userId
      console.log('用户ID:', userId)
      
      // 验证必填字段
      if (!scheduleData.match_id || !scheduleData.date || !scheduleData.venue) {
        return { code: 400, message: '缺少必填字段' }
      }
      
      if (!scheduleData.time_slots || scheduleData.time_slots.length === 0) {
        return { code: 400, message: '至少需要一个时段' }
      }
      
      // 获取操作模式：'create' 创建新日程，'edit' 编辑现有日程
      const mode = scheduleData.mode || 'create'
      const scheduleId = scheduleData.schedule_id || null
      const isDraft = scheduleData.is_draft || false // 是否保存为草稿
      
      console.log('操作模式:', mode, '日程ID:', scheduleId, '是否草稿:', isDraft)
      
      // 处理裁判需求数据
      const processRefereeRequirements = (requirements) => {
        if (!requirements || typeof requirements !== 'object') {
          return {}
        }
        
        // 确保数据格式正确
        const processed = {}
        Object.keys(requirements).forEach(key => {
          const count = parseInt(requirements[key])
          if (count > 0) {
            processed[key] = count
          }
        })
        
        return processed
      }
      
      const processedTimeSlots = scheduleData.time_slots.map(slot => ({
        ...slot,
        referee_requirements: processRefereeRequirements(slot.referee_requirements),
        applications: [] // 初始化报名列表
      }))
      
      // 准备保存的日程数据
      const scheduleDoc = {
        match_id: scheduleData.match_id,
        date: scheduleData.date,
        venue: scheduleData.venue,
        time_slots: processedTimeSlots,
        status: isDraft ? 'draft' : 'open', // 草稿状态或正式发布状态
        organizer_id: userId,
        create_time: new Date(),
        update_time: new Date()
      }
      
      let result
      let isNewSchedule = false
      
      if (mode === 'edit') {
        // 编辑模式：更新指定的日程
        if (!scheduleId) {
          return { code: 400, message: '编辑模式需要提供日程ID' }
        }
        
        // 验证日程是否存在
        const existingSchedule = await db.collection('match_schedules')
          .doc(scheduleId)
          .get()
        
        if (!existingSchedule.data.length) {
          return { code: 404, message: '要编辑的日程不存在' }
        }
        
        // 更新日程
        result = await db.collection('match_schedules')
          .doc(scheduleId)
          .update({
            ...scheduleDoc,
            update_time: new Date()
          })
        console.log('更新日程结果:', result)
        
              } else {
        // 创建模式：直接创建新日程，不再检查日期冲突
        result = await db.collection('match_schedules')
          .add(scheduleDoc)
        console.log('创建日程结果:', result)
        isNewSchedule = true
      }
      
      // 只有创建新的正式发布日程时才发送通知（草稿不发送通知）
      if (isNewSchedule && !isDraft) {
        try {
          const notificationService = uniCloud.importObject('notification-service');
          
          // 获取比赛信息
          const matchResult = await db.collection('matches').doc(scheduleData.match_id).get();
          const matchTitle = matchResult.data && matchResult.data.length > 0 ? 
            matchResult.data[0].title : '比赛';
          
          // 获取全平台用户
          const userCollection = db.collection('users');
          const usersResult = await userCollection.field({
            _id: true
          }).get();
          
          if (usersResult.data && usersResult.data.length > 0) {
            const userIds = usersResult.data.map(user => user._id);
            
            // 构建多时段日程通知内容
            const slotCount = processedTimeSlots.length;
            const timeRange = processedTimeSlots.length > 0 ? 
              `${processedTimeSlots[0].start_time}-${processedTimeSlots[processedTimeSlots.length - 1].end_time}` : 
              '时间待定';
            
            await notificationService.batchSendNotification({
              userIds: userIds,
              type: 'match_publish',
              title: `多时段比赛日程发布：${matchTitle}`,
              content: `${matchTitle} 的多时段比赛日程已发布！日期：${scheduleData.date}，地点：${scheduleData.venue}，时段：${timeRange}，共${slotCount}个时段。各时段执裁需求已开放申请！`,
              relatedId: scheduleData.match_id,
              senderId: userId,
              extraData: {
                jump_type: 'match_detail',
                jump_url: `/packgeCompetition/competition/detail?id=${scheduleData.match_id}`,
                match_id: scheduleData.match_id,
                schedule_id: result.id || existingSchedule.data[0]._id,
                match_date: scheduleData.date,
                venue: scheduleData.venue,
                slot_count: slotCount
              }
            });
            
            console.log(`多时段比赛日程创建通知已发送给全平台 ${userIds.length} 名用户`);
          }
        } catch (notifyError) {
          console.error('发送多时段比赛日程创建通知失败:', notifyError);
          // 不影响日程创建的主流程
        }
      }
      
      // 构建成功消息
      let successMessage = ''
      if (mode === 'edit') {
        successMessage = isDraft ? '草稿更新成功' : '日程更新成功'
      } else {
        successMessage = isDraft ? '草稿保存成功' : '日程发布成功'
      }
      
      return {
        code: 0,
        message: successMessage,
        data: {
          id: mode === 'edit' ? scheduleId : result.id,
          mode: mode,
          isDraft: isDraft,
          isNewSchedule: isNewSchedule,
          status: scheduleDoc.status,
          ...scheduleDoc
        }
      }
      
    } catch (error) {
      console.error('创建多时段比赛日程失败:', error)
      return {
        code: 500,
        message: '服务器错误: ' + error.message
      }
    }
  },

  /**
   * 申请时段裁判职位（修复数据同步问题）
   */
  async applyForSlotReferee(applicationData) {
    try {
      console.log('开始申请时段裁判职位:', applicationData)
      
      // 获取token
      const token = this.getUniIdToken()
      if (!token) {
        return { code: 401, message: '未登录或登录状态已过期' }
      }
      
      // 使用user-service验证token
      const userService = uniCloud.importObject('user-service')
      const tokenResult = await userService.verifyToken({ token })
      
      if (tokenResult.code !== 0) {
        console.error('Token验证失败:', tokenResult)
        return { code: 401, message: tokenResult.message || 'Token验证失败' }
      }
      
      const userId = tokenResult.data.userId
      console.log('申请用户ID:', userId)
      
      // 直接从数据库获取用户详细信息进行权限验证（避免网络调用超时）
      const userDoc = await db.collection('users').doc(userId).get()
      
      if (!userDoc.data || userDoc.data.length === 0) {
        console.error('用户不存在:', userId)
        return { code: 404, message: '用户不存在' }
      }
      
      const userInfo = userDoc.data[0]
      console.log('用户信息:', userInfo)
      
      // 权限检查：优先检查认证状态，再检查角色
      const userRole = userInfo.role
      const credentialStatus = userInfo.credential_status
      const allowedRoles = [1, 3, '1', '3']
      
      console.log('权限检查 - 用户角色:', userRole, '认证状态:', credentialStatus)
      
      // 1. 首先检查认证状态：必须通过身份资质认证
      if (credentialStatus !== 'approved') {
        return {
          code: 403,
          message: '您还未通过身份资质认证，请先申请资质认证',
          reason: 'not_certified',
          needCertification: true
        }
      }
      
      // 2. 然后检查用户角色：只有裁判员(1)和裁判监督(3)可以报名
      if (!allowedRoles.includes(userRole)) {
        return {
          code: 403,
          message: '只有裁判员和裁判监督可以报名比赛选派',
          reason: 'role_not_allowed'
        }
      }
      
      console.log('用户权限验证通过，角色:', userRole, '认证状态:', credentialStatus)
      
      // 验证必填字段
      const { schedule_id, slot_id, position, reason, contact_phone, preferred_positions, auto_apply_mode } = applicationData
      if (!schedule_id || !slot_id || !position) {
        return { code: 400, message: '缺少必填字段' }
      }
      
      // 获取日程信息
      const scheduleDoc = await db.collection('match_schedules')
        .doc(schedule_id)
        .get()
      
      if (!scheduleDoc.data.length) {
        return { code: 404, message: '日程不存在' }
      }
      
      const schedule = scheduleDoc.data[0]
      const targetSlot = schedule.time_slots.find(slot => slot.slot_id === slot_id)
      
      if (!targetSlot) {
        return { code: 404, message: '时段不存在' }
      }
      
      // 检查该时段是否已完成最终选派确认
      const currentApplications = targetSlot.applications || []
      const hasConfirmedApplication = currentApplications.some(app => app.status === 'confirmed')
      
      if (hasConfirmedApplication) {
        return { 
          code: 403, 
          message: '该时段已完成最终选派确认，不再接受新的报名申请',
          reason: 'selection_finalized'
        }
      }
      
      // 检查用户是否已经申请过该时段的该职位
      const existingApplication = currentApplications.find(app => 
        app.user_id === userId && 
        app.position === position && 
        app.status !== 'cancelled'
      )
      
      if (existingApplication) {
        return { code: 400, message: '您已经申请过该职位' }
      }
      
      // 创建申请记录
      const application = {
        application_id: 'app_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
        user_id: userId,
        position: position,
        reason: reason || '',
        contact_phone: contact_phone || '',
        preferred_positions: preferred_positions || [], // 新增：意向岗位信息
        auto_apply_mode: auto_apply_mode || false, // 新增：自动报名模式标识
        status: 'pending',
        apply_time: new Date(),
        create_time: new Date()
      }
      
      // 更新日程文档中的申请列表
      const updatedTimeSlots = schedule.time_slots.map(slot => {
        if (slot.slot_id === slot_id) {
          return {
            ...slot,
            applications: [...(slot.applications || []), application]
          }
        }
        return slot
      })
      
      // 执行数据库更新（关键修复点：确保事务性）
      const updateResult = await db.collection('match_schedules')
        .doc(schedule_id)
        .update({
          time_slots: updatedTimeSlots,
          update_time: new Date()
        })
      
      console.log('更新日程申请列表结果:', updateResult)
      
      // 验证更新是否成功
      if (updateResult.updated === 0) {
        console.error('数据库更新失败，未更新任何记录')
        return { code: 500, message: '申请提交失败，请重试' }
      }
      
      // 同时在match_applications表中创建记录（双重保险）
      try {
        await db.collection('match_applications').add({
          match_id: schedule.match_id,
          schedule_id: schedule_id,
          slot_id: slot_id,
          user_id: userId,
          position: position,
          status: 'pending',
          apply_reason: reason || '',
          contact_info: contact_phone || '',
          preferred_positions: preferred_positions || [], // 新增：意向岗位信息
          auto_apply_mode: auto_apply_mode || false, // 新增：自动报名模式标识
          apply_time: new Date(),
          create_time: new Date(),
          update_time: new Date()
        })
        console.log('同步创建match_applications记录成功')
      } catch (syncError) {
        console.error('同步创建match_applications记录失败:', syncError)
        // 不影响主流程，仅记录错误
      }
      
      return {
        code: 0,
        message: '申请提交成功',
        data: {
          application_id: application.application_id,
          status: 'pending'
        }
      }
      
    } catch (error) {
      console.error('申请时段裁判职位失败:', error)
      return {
        code: 500,
        message: '服务器错误: ' + error.message
      }
    }
  },

  /**
   * 取消时段裁判职位申请（支持批量取消同一时段的所有申请）
   */
  async cancelSlotRefereeApplication(cancelData) {
    try {
      console.log('开始取消时段裁判职位申请:', cancelData)
      
      // 获取token
      const token = this.getUniIdToken()
      if (!token) {
        return { code: 401, message: '未登录或登录状态已过期' }
      }
      
      // 使用user-service验证token
      const userService = uniCloud.importObject('user-service')
      const tokenResult = await userService.verifyToken({ token })
      
      if (tokenResult.code !== 0) {
        console.error('Token验证失败:', tokenResult)
        return { code: 401, message: tokenResult.message || 'Token验证失败' }
      }
      
      const userId = tokenResult.data.userId
      
      // 验证必填字段（application_id 改为可选，用于单个取消的兼容）
      const { schedule_id, slot_id, application_id } = cancelData
      if (!schedule_id || !slot_id) {
        return { code: 400, message: '缺少必填字段' }
      }
      
      // 获取日程信息
      const scheduleDoc = await db.collection('match_schedules')
        .doc(schedule_id)
        .get()
      
      if (!scheduleDoc.data.length) {
        return { code: 404, message: '日程不存在' }
      }
      
      const schedule = scheduleDoc.data[0]
      const targetSlot = schedule.time_slots.find(slot => slot.slot_id === slot_id)
      
      if (!targetSlot) {
        return { code: 404, message: '时段不存在' }
      }
      
      // 查找该用户在该时段的所有申请记录
      const applications = targetSlot.applications || []
      const userApplications = applications.filter(app => 
        app.user_id === userId && app.status !== 'cancelled'
      )
      
      if (userApplications.length === 0) {
        return { code: 404, message: '没有找到可取消的申请记录' }
      }
      
      console.log(`找到用户 ${userId} 在时段 ${slot_id} 的 ${userApplications.length} 个申请`)
      
      // 检查每个申请的状态，确保都可以取消
      const notCancellableApps = []
      const cancellableApps = []
      
      for (const app of userApplications) {
        console.log(`检查申请状态: ${app.position} - ${app.status}`)
        
        if (app.status === 'confirmed') {
          notCancellableApps.push({
            position: app.position,
            reason: '已完成最终选派确认，无法取消'
          })
        } else if (app.status === 'selected') {
          notCancellableApps.push({
            position: app.position,
            reason: '已被选派，无法取消'
          })
        } else if (app.status === 'rejected') {
          notCancellableApps.push({
            position: app.position,
            reason: '已被拒绝，无法取消'
          })
        } else if (app.status === 'pending') {
          cancellableApps.push(app)
        } else {
          notCancellableApps.push({
            position: app.position,
            reason: `状态"${app.status}"不允许取消`
          })
        }
      }
      
      // 如果没有可取消的申请
      if (cancellableApps.length === 0) {
        const reasons = notCancellableApps.map(app => `${app.position}: ${app.reason}`).join('; ')
        return { 
          code: 400, 
          message: `没有可取消的申请。${reasons}`,
          reason: 'no_cancellable_applications'
        }
      }
      
      console.log(`可取消申请: ${cancellableApps.length}个，不可取消: ${notCancellableApps.length}个`)
      
      // 批量更新申请状态
      const now = new Date()
      const updatedApplications = applications.map(app => {
        // 如果是该用户的可取消申请，更新状态
        const cancellableApp = cancellableApps.find(cancelApp => 
          cancelApp.application_id === app.application_id
        )
        
        if (cancellableApp) {
          return {
            ...app,
            status: 'cancelled',
            cancel_time: now,
            update_time: now
          }
        }
        
        return app
      })
      
      // 更新日程文档
      const updatedTimeSlots = schedule.time_slots.map(slot => {
        if (slot.slot_id === slot_id) {
          return {
            ...slot,
            applications: updatedApplications
          }
        }
        return slot
      })
      
      const updateResult = await db.collection('match_schedules')
        .doc(schedule_id)
        .update({
          time_slots: updatedTimeSlots,
          update_time: now
        })
      
      console.log('取消申请更新结果:', updateResult)
      
      // 同步更新match_applications表 - 批量更新该用户在该时段的所有pending申请
      try {
        const batchUpdateResult = await db.collection('match_applications')
          .where({
            schedule_id: schedule_id,
            slot_id: slot_id,
            user_id: userId,
            status: 'pending'
          })
          .update({
            status: 'cancelled',
            cancel_time: now,
            update_time: now
          })
        
        console.log('批量更新match_applications结果:', batchUpdateResult)
      } catch (syncError) {
        console.error('同步更新match_applications失败:', syncError)
        // 不影响主流程，仅记录错误
      }
      
      // 构建返回结果
      const cancelledPositions = cancellableApps.map(app => app.position)
      let message = `成功取消${cancellableApps.length}个申请`
      
      if (notCancellableApps.length > 0) {
        const failedInfo = notCancellableApps.map(app => `${app.position}: ${app.reason}`).join('; ')
        message += `，部分申请无法取消: ${failedInfo}`
      }
      
      return {
        code: 0,
        message: message,
        data: {
          cancelled_count: cancellableApps.length,
          cancelled_positions: cancelledPositions,
          not_cancellable_count: notCancellableApps.length,
          not_cancellable_details: notCancellableApps
        }
      }
      
    } catch (error) {
      console.error('取消时段裁判职位申请失败:', error)
      return {
        code: 500,
        message: '服务器错误: ' + error.message
      }
    }
  },

  /**
   * 获取时段申请列表 - 从match_applications表获取
   */
  async getSlotApplications(params) {
    try {
      console.log('getSlotApplications 开始执行，参数:', params);
      
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { sessionId } = params;

      console.log('查询申请列表，用户ID:', userId, '时段ID:', sessionId);

      if (!sessionId) {
        return {
          code: -1,
          message: '时段ID不能为空'
        };
      }

      // 获取申请列表 - 从match_applications表查询（排除已取消的申请）
      const result = await db.collection('match_applications')
        .where({ 
          slot_id: sessionId,
          status: db.command.neq('cancelled')  // 排除已取消的申请
        })
        .orderBy('apply_time', 'desc')
        .get();

      console.log('查询到的申请数量:', result.data.length);
      console.log('申请数据详情:', result.data);

      // 获取申请者的用户信息
      const applications = [];
      for (const app of result.data) {
        try {
          console.log('处理申请:', app._id, '用户ID:', app.user_id);
          
          // 检查用户ID是否有效
          if (!app.user_id) {
            console.error('用户ID为空');
            throw new Error('用户ID为空');
          }
          
          // 直接从认证表获取用户信息
          console.log('开始获取认证信息');
          
          let credentialInfo = {
            real_name: '',
            phone: '',
            gender: '',
            age: '',
            level: '',
            identity: '普通用户',
            register_organization: '',
            register_date: ''
          };

          // 先查询裁判员认证
          const refereeResult = await db.collection('referee_credentials')
            .where({ 
              user_id: app.user_id,
              status: 'approved' 
            })
            .orderBy('create_time', 'desc')
            .limit(1)
            .get();

          console.log('裁判员认证查询结果:', refereeResult.data.length);
          if (refereeResult.data.length > 0) {
            const referee = refereeResult.data[0];
            console.log('裁判员认证信息:', referee);
            credentialInfo = {
              real_name: referee.real_name || '',
              phone: '', // 认证表中没有手机号
              gender: referee.gender || '',
              age: referee.age || '',
              level: (() => {
                const levelMap = {
                  1: '三级裁判员',
                  2: '二级裁判员',
                  3: '一级裁判员',
                  4: '预备国家级裁判员',
                  5: '国家级裁判员',
                  6: '国际级裁判员'
                };
                return levelMap[referee.level] || '';
              })(),
              identity: '裁判员',
              register_organization: referee.register_organization || '',
              register_date: referee.register_date || ''
            };
          } else {
            // 查询裁判监督认证
            const supervisorResult = await db.collection('supervisor_credentials')
              .where({ 
                user_id: app.user_id,
                status: 'approved' 
              })
              .orderBy('create_time', 'desc')
              .limit(1)
              .get();

            console.log('裁判监督认证查询结果:', supervisorResult.data.length);
            if (supervisorResult.data.length > 0) {
              const supervisor = supervisorResult.data[0];
              console.log('裁判监督认证信息:', supervisor);
              credentialInfo = {
                real_name: supervisor.real_name || '',
                phone: '', // 认证表中没有手机号
                gender: supervisor.gender || '',
                age: supervisor.age || '',
                level: '', // 裁判监督没有等级
                identity: '裁判监督',
                register_organization: supervisor.register_organization || '',
                register_date: supervisor.register_date || ''
              };
            }
          }
          
          console.log('获取到的认证信息:', credentialInfo);
          
          // 检查时间冲突 - 暂时跳过，避免方法调用问题
          const conflicts = [];
          
          // 获取手机号：优先级为 报名时填写的手机号 > 认证表中的手机号 > 默认值
          let phoneNumber = '未提供'
          if (app.contact_info) {
            phoneNumber = app.contact_info
          } else if (credentialInfo.phone) {
            phoneNumber = credentialInfo.phone
          }
          
          // 构建最终用户信息
          const finalUserInfo = {
            name: credentialInfo.real_name || '匿名用户',
            phone: phoneNumber,
            gender: credentialInfo.gender || '未知',
            age: credentialInfo.age || '未知',
            referee_level: credentialInfo.level || '',
            referee_identity: credentialInfo.identity || '普通用户',
            register_organization: credentialInfo.register_organization || '未知',
            certification_date: credentialInfo.register_date || '',
            experience: 0  // 执裁记录，暂时设为0，后续完善
          };
          
          console.log('最终用户信息:', finalUserInfo);
          
          applications.push({
            ...app,
            user_info: finalUserInfo,
            user_name: finalUserInfo.name,
            contact_info: phoneNumber, // 使用统一的手机号获取逻辑
            // 添加从match_applications表的字段映射
            application_time: app.apply_time,  // 统一字段名
            review_note: app.review_comment || app.apply_reason || '',  // 使用review_comment或apply_reason作为备注
            conflicts: conflicts  // 时间冲突信息
          });
        } catch (error) {
          console.error('获取用户信息失败:', error);
          // 如果获取用户信息失败，使用默认信息
          const fallbackPhoneNumber = app.contact_info || '未提供'
          
          const defaultUserInfo = {
              name: '匿名用户',
              phone: fallbackPhoneNumber,
              gender: '未知',
            age: '未知',
            referee_level: '',
            referee_identity: '普通用户',
            register_organization: '未知',
            certification_date: '',
              experience: 0
          };
          
          applications.push({
            ...app,
            user_info: defaultUserInfo,
            user_name: defaultUserInfo.name,
            contact_info: fallbackPhoneNumber,
            // 添加从match_applications表的字段映射
            application_time: app.apply_time,  // 统一字段名
            review_note: app.review_comment || app.apply_reason || '',
            conflicts: []
          });
        }
      }

      console.log('最终处理的申请数量:', applications.length);

      return {
        code: 0,
        message: '获取成功',
        data: applications
      };
      
    } catch (error) {
      console.error('获取申请列表失败:', error);
      return {
        code: -1,
        message: '获取申请列表失败: ' + error.message
      };
    }
  },

  /**
   * 审核时段申请（扩展状态支持）
   */
  async reviewSlotApplication(params) {
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { applicationId, status, comment } = params;

      if (!applicationId || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }

      // 扩展支持的状态：pending, selected, confirmed, rejected
      if (!['pending', 'selected', 'confirmed', 'rejected'].includes(status)) {
        return {
          code: -1,
          message: '无效的审核状态'
        };
      }

      // 获取申请信息
      const appResult = await db.collection('match_applications')
        .doc(applicationId)
        .get();

      if (!appResult.data.length) {
        return {
          code: -1,
          message: '申请不存在'
        };
      }

      const application = appResult.data[0];

      // 验证状态流转合法性
      const currentStatus = application.status;
      const validTransitions = {
        'pending': ['selected', 'rejected'],
        'selected': ['pending', 'confirmed'],  // selected可以撤回到pending或确认为confirmed
        'confirmed': [],  // confirmed是最终状态，不可变更
        'rejected': []    // rejected是最终状态，不可变更
      };

      if (!validTransitions[currentStatus] || !validTransitions[currentStatus].includes(status)) {
        return {
          code: -1,
          message: `无法从${currentStatus}状态变更为${status}状态`
        };
      }

      // 验证审核权限（需要是比赛发布者）
      const scheduleResult = await db.collection('match_schedules')
        .doc(application.schedule_id)
        .get();

      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '时段不存在'
        };
      }

      const schedule = scheduleResult.data[0];
      
      // 获取比赛信息验证权限
      const matchResult = await db.collection('matches')
        .doc(schedule.match_id)
        .get();

      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      const match = matchResult.data[0];
      
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '只有比赛发布者才能审核申请'
        };
      }

      // 更新申请状态
      const now = new Date();
      const updateData = {
        status: status,
        update_time: now
      };

      // 根据状态添加相应的时间戳
      switch (status) {
        case 'selected':
          updateData.selected_time = now;
          updateData.selected_by = userId;
          break;
        case 'confirmed':
          updateData.confirmed_time = now;
          updateData.confirmed_by = userId;
          break;
        case 'rejected':
          updateData.rejected_time = now;
          updateData.rejected_by = userId;
          if (comment) {
            updateData.reject_reason = comment;
          }
          break;
        case 'pending':
          // 撤回选派时清除选派时间
          updateData.selected_time = null;
          updateData.selected_by = null;
          break;
      }

      await db.collection('match_applications')
        .doc(applicationId)
        .update(updateData);

      // 如果状态变为selected（被选派），自动取消同一用户在同一时段的其他pending申请
      if (status === 'selected') {
        try {
          // 【强化】使用事务确保自动取消的原子性
          const autoTransaction = await db.startTransaction()
          
          try {
            // 查找同一用户在同一时段的其他pending申请
            const otherApplicationsResult = await autoTransaction.collection('match_applications')
              .where({
                schedule_id: application.schedule_id,
                slot_id: application.slot_id,
                user_id: application.user_id,
                status: 'pending',
                _id: db.command.neq(applicationId) // 排除当前申请
              })
              .get();

            if (otherApplicationsResult.data.length > 0) {
              console.log(`用户${application.user_id}在时段${application.slot_id}已被选派，发现${otherApplicationsResult.data.length}个pending申请，将自动取消`);
              
              // 批量取消其他pending申请
              const cancelPromises = otherApplicationsResult.data.map(otherApp => 
                autoTransaction.collection('match_applications')
                  .doc(otherApp._id)
                  .update({
                    status: 'cancelled',
                    cancel_time: now,
                    cancel_reason: '用户已被选派其他岗位，系统自动取消',
                    cancelled_by_system: true, // 标记为系统自动取消
                    update_time: now
                  })
              );
              
              await Promise.all(cancelPromises);
              
              // 【新增】记录自动取消操作日志
              await autoTransaction.collection('operation_logs').add({
                operation_type: 'auto_cancel_applications',
                operator_id: userId,
                target_type: 'batch_applications',
                target_id: application.slot_id,
                operation_data: {
                  schedule_id: application.schedule_id,
                  slot_id: application.slot_id,
                  user_id: application.user_id,
                  selected_application_id: applicationId,
                  cancelled_applications: otherApplicationsResult.data.map(app => ({
                    id: app._id,
                    position: app.position
                  }))
                },
                operation_time: now,
                client_info: this.clientInfo
              });
              
              console.log(`成功自动取消${otherApplicationsResult.data.length}个pending申请`);
            }
            
            // 提交自动取消事务
            await autoTransaction.commit()
            
          } catch (autoTransactionError) {
            await autoTransaction.rollback()
            console.error('自动取消其他申请事务失败:', autoTransactionError);
            // 继续执行主流程，但记录错误
          }
          
        } catch (autoCancelError) {
          console.error('自动取消其他申请失败:', autoCancelError);
          // 不影响主流程，但记录错误
        }
      }

      // 【强化】状态变更时的额外验证
      if (status === 'confirmed') {
        // 确认选派前，再次验证申请状态
        const finalVerifyResult = await db.collection('match_applications')
          .doc(applicationId)
          .get();
          
        if (!finalVerifyResult.data.length || finalVerifyResult.data[0].status !== 'selected') {
          return {
            code: -1,
            message: '申请状态已变更，无法确认选派'
          };
        }
        
        // 【新增】检查同一时段是否有重复确认的风险
        const duplicateCheck = await db.collection('match_applications')
          .where({
            schedule_id: application.schedule_id,
            slot_id: application.slot_id,
            user_id: application.user_id,
            status: 'confirmed'
          })
          .get();
          
        if (duplicateCheck.data.length > 0) {
          return {
            code: -1,
            message: '该用户在此时段已有确认的选派，无法重复确认'
          };
        }
      }

      // 同步更新 match_schedules 集合中的申请状态
      try {
        const targetSlotIndex = schedule.time_slots.findIndex(slot => slot.slot_id === application.slot_id);
        
        if (targetSlotIndex !== -1) {
          const targetSlot = schedule.time_slots[targetSlotIndex];
          const applicationIndex = targetSlot.applications?.findIndex(app => app._id === applicationId);
          
          if (applicationIndex !== -1) {
            // 更新时段中的申请状态
            const updatedApplications = [...(targetSlot.applications || [])];
            updatedApplications[applicationIndex] = {
              ...updatedApplications[applicationIndex],
              status: status,
              update_time: now,
              ...updateData
            };
            
            // 如果是selected状态（被选派），同时更新同一用户的其他pending申请为cancelled
            if (status === 'selected') {
              updatedApplications.forEach((app, index) => {
                if (app.user_id === application.user_id && 
                    app._id !== applicationId && 
                    app.status === 'pending') {
                  updatedApplications[index] = {
                    ...app,
                    status: 'cancelled',
                    cancel_time: now,
                    cancel_reason: '用户已被选派其他岗位，自动取消',
                    update_time: now
                  };
                }
              });
            }
            
            // 更新整个时段的申请数组
            const updatedTimeSlots = [...schedule.time_slots];
            updatedTimeSlots[targetSlotIndex] = {
              ...targetSlot,
              applications: updatedApplications
            };
            
            // 更新 match_schedules 集合
            await db.collection('match_schedules')
              .doc(application.schedule_id)
              .update({
                time_slots: updatedTimeSlots,
                update_time: now
              });
          }
        }
      } catch (syncError) {
        console.error('同步更新 match_schedules 失败:', syncError);
        // 不影响主流程，但记录错误
      }

      // 发送审核结果通知
      try {
        if (status === 'rejected') {
          // 发送审核拒绝通知
          const notificationService = uniCloud.importObject('notification-service');
          
          // 获取详细的比赛信息用于通知内容
          const matchTitle = match.title || '未知比赛';
          const rejectReason = comment ? `拒绝原因：${comment}` : '';
          
          // 查找对应的时段信息
          const targetSlot = schedule.time_slots?.find(slot => slot.slot_id === application.slot_id);
          
          // 构建详细的比赛信息
          let matchDetail = `比赛：${matchTitle}`;
          
          if (targetSlot) {
            const matchDate = schedule.date ? new Date(schedule.date).toLocaleDateString('zh-CN') : '日期待定';
            const matchTime = `${targetSlot.start_time || '时间'}-${targetSlot.end_time || '待定'}`;
            const matchVenue = targetSlot.venue || schedule.venue || '场地待定';
            const matchTeams = `${targetSlot.home_team || '主队'} vs ${targetSlot.away_team || '客队'}`;
            
            matchDetail = `比赛：${matchTitle}，日期：${matchDate}，时间：${matchTime}，场地：${matchVenue}，对阵：${matchTeams}`;
          }
          
          // 获取申请的岗位信息
          const positionMap = {
            'main_referee': '主裁判',
            'assistant_referee': '助理裁判', 
            'fourth_official': '第四官员',
            'referee_supervisor': '裁判监督'
          };
          const position = positionMap[application.position] || application.position || '裁判';
          
          const detailContent = `很抱歉，您申请的${position}岗位未通过审核。${matchDetail}。${rejectReason}`;
          
          await notificationService.sendNotification({
            userId: application.user_id,
            type: 'match_review',
            title: '比赛选派申请审核结果',
            content: detailContent,
            relatedId: match._id,
            senderId: userId,
            extraData: {
              jump_type: 'match_detail',
              jump_url: `/packgeCompetition/competition/detail?id=${match._id}`,
              match_id: match._id,
              slot_id: application.slot_id,
              position: application.position,
              review_result: 'rejected',
              reject_reason: comment
            }
          });
          
        }
      } catch (notifyError) {
        console.error('发送审核通知失败:', notifyError);
        // 不影响审核的主流程
      }

      // 返回相应的消息
      const statusMessages = {
        'selected': '初步选派成功',
        'confirmed': '最终确认选派',
        'rejected': '已拒绝申请',
        'pending': '已撤回选派'
      };

      return {
        code: 0,
        message: statusMessages[status] || '状态更新成功',
        data: {
          applicationId,
          status,
          updateTime: now
        }
      };
      
    } catch (error) {
      console.error('审核申请失败:', error);
      return {
        code: -1,
        message: '审核申请失败'
      };
    }
  },

  /**
   * 撤回选派
   */
  async revokeSlotSelection(params) {
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { applicationId } = params;
      
      console.log('撤回选派 - 参数信息:', {
        userId: userId,
        applicationId: applicationId
      });
      
      if (!applicationId) {
        return {
          code: -1,
          message: '申请ID不能为空'
        };
      }
      
      // 直接进行撤回操作，不调用其他方法
      console.log('开始撤回选派操作');
      
      // 获取申请信息
      const appResult = await db.collection('match_applications')
        .doc(applicationId)
        .get();

      if (!appResult.data.length) {
        return {
          code: -1,
          message: '申请不存在'
        };
      }

      const application = appResult.data[0];

      // 验证状态流转合法性
      const currentStatus = application.status;
      if (currentStatus !== 'selected') {
        return {
          code: -1,
          message: `无法撤回，当前状态为${currentStatus}`
        };
      }

      // 验证审核权限（需要是比赛发布者）
      const scheduleResult = await db.collection('match_schedules')
        .doc(application.schedule_id)
        .get();

      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '时段不存在'
        };
      }

      const schedule = scheduleResult.data[0];
      
      // 获取比赛信息验证权限
      const matchResult = await db.collection('matches')
        .doc(schedule.match_id)
        .get();

      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      const match = matchResult.data[0];
      
      console.log('权限验证 - 比赛信息:', {
        match_id: match._id,
        publisher_id: match.publisher_id,
        current_userId: userId
      });
      
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '只有比赛发布者才能撤回选派'
        };
      }

      // 更新申请状态
      const now = new Date();
      const updateData = {
        status: 'pending',
        update_time: now,
        selected_time: null,
        selected_by: null
      };

      await db.collection('match_applications')
        .doc(applicationId)
        .update(updateData);

      // 同步更新 match_schedules 集合中的申请状态
      try {
        const targetSlotIndex = schedule.time_slots.findIndex(slot => slot.slot_id === application.slot_id);
        if (targetSlotIndex !== -1) {
          const targetSlot = schedule.time_slots[targetSlotIndex];
          const applicationIndex = targetSlot.applications?.findIndex(app => app._id === applicationId);
          
          if (applicationIndex !== -1) {
            // 更新时段中的申请状态
            const updatedApplications = [...(targetSlot.applications || [])];
            updatedApplications[applicationIndex] = {
              ...updatedApplications[applicationIndex],
              status: 'pending',
              update_time: now,
              selected_time: null,
              selected_by: null
            };
            
            // 更新整个时段的申请数组
            const updatedTimeSlots = [...schedule.time_slots];
            updatedTimeSlots[targetSlotIndex] = {
              ...targetSlot,
              applications: updatedApplications
            };
            
            // 更新 match_schedules 集合
            await db.collection('match_schedules')
              .doc(application.schedule_id)
              .update({
                time_slots: updatedTimeSlots,
                update_time: now
              });
          }
        }
      } catch (syncError) {
        console.error('同步更新 match_schedules 失败:', syncError);
        // 不影响主流程，但记录错误
      }

      return {
        code: 0,
        message: '已撤回选派',
        data: {
          applicationId,
          status: 'pending',
          updateTime: now
        }
      };
    } catch (error) {
      console.error('撤回选派失败:', error);
      return {
        code: -1,
        message: '撤回选派失败: ' + error.message
      };
    }
  },

  /**
   * 完成选派（批量确认）
   */
  async completeSlotSelection(params) {
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { sessionId } = params;

      if (!sessionId) {
        return {
          code: -1,
          message: '时段ID不能为空'
        };
      }

      // 获取该时段所有selected状态的申请
      const applicationsResult = await db.collection('match_applications')
        .where({
          slot_id: sessionId,
          status: 'selected'
        })
        .get();

      if (applicationsResult.data.length === 0) {
        return {
          code: -1,
          message: '没有待确认的选派'
        };
      }

      // 验证权限
      const firstApp = applicationsResult.data[0];
      const scheduleResult = await db.collection('match_schedules')
        .doc(firstApp.schedule_id)
        .get();

      if (!scheduleResult.data.length) {
        return {
          code: -1,
          message: '时段不存在'
        };
      }

      const schedule = scheduleResult.data[0];
      const matchResult = await db.collection('matches')
        .doc(schedule.match_id)
        .get();

      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      const match = matchResult.data[0];
      
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '只有比赛发布者才能完成选派'
        };
      }

      // 批量更新所有selected状态的申请为confirmed
      const now = new Date();
      const updatePromises = applicationsResult.data.map(app => 
        db.collection('match_applications')
          .doc(app._id)
        .update({
            status: 'confirmed',
            confirmed_time: now,
            confirmed_by: userId,
          update_time: now
          })
      );

      await Promise.all(updatePromises);

      // 同步更新 match_schedules 集合中的申请状态
      try {
        const targetSlotIndex = schedule.time_slots.findIndex(slot => slot.slot_id === sessionId);
        if (targetSlotIndex !== -1) {
          const targetSlot = schedule.time_slots[targetSlotIndex];
          
          // 批量更新时段中的申请状态
          const updatedApplications = [...(targetSlot.applications || [])];
          applicationsResult.data.forEach(app => {
            const applicationIndex = updatedApplications.findIndex(slotApp => slotApp._id === app._id);
            if (applicationIndex !== -1) {
              updatedApplications[applicationIndex] = {
                ...updatedApplications[applicationIndex],
                status: 'confirmed',
                confirmed_time: now,
                confirmed_by: userId,
                update_time: now
              };
            }
          });
          
          // 更新整个时段的申请数组
          const updatedTimeSlots = [...schedule.time_slots];
          updatedTimeSlots[targetSlotIndex] = {
            ...targetSlot,
            applications: updatedApplications
          };
          
          // 更新 match_schedules 集合
          await db.collection('match_schedules')
            .doc(firstApp.schedule_id)
            .update({
              time_slots: updatedTimeSlots,
              update_time: now
            });
            
                  }
      } catch (syncError) {
        console.error('同步更新 match_schedules 失败:', syncError);
        // 不影响主流程，但记录错误
      }

      // 发送最终选派确认通知给所有确认的申请人
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        // 找到对应的时段信息
        const targetSlot = schedule.time_slots?.find(slot => slot.slot_id === sessionId);
        const matchTimeSlot = targetSlot ? `${targetSlot.start_time}-${targetSlot.end_time}` : '时段未定';
        const matchTeams = targetSlot ? `${targetSlot.home_team || '主队'} vs ${targetSlot.away_team || '客队'}` : '对阵待定';
        
        // 批量发送通知
        const userIds = applicationsResult.data.map(app => app.user_id);
        
        const notificationParams = {
          userIds: userIds,
          type: 'match_review',
          title: '比赛选派最终确认',
          content: `恭喜！您的比赛申请已最终确认选派。比赛：${match.title}，时段：${matchTimeSlot}，对阵：${matchTeams}。请按时参加比赛，执裁记录已自动生成。`,
          relatedId: match._id,
          senderId: userId,
          extraData: {
            jump_type: 'selection_table',
            jump_url: `/packageMy/my/schedule-viewer?sessionId=${sessionId}&role=referee&viewMode=confirmed`,
            match_id: match._id,
            session_id: sessionId,
            match_time_slot: matchTimeSlot,
            review_result: 'confirmed',
            // 添加选派表相关数据
            selection_data: {
              session_ids: [sessionId],
              viewer_role: 'referee',
              only_confirmed: true
            }
          }
        };
        
        console.log('通知参数:', JSON.stringify(notificationParams, null, 2));
        
        const notifyResult = await notificationService.batchSendNotification(notificationParams);
        console.log('通知发送结果:', notifyResult);
        
        if (notifyResult.code === 0) {
          console.log(`✅ 最终选派确认通知发送成功，共 ${userIds.length} 名用户`);
        } else {
          console.error(`❌ 通知发送失败:`, notifyResult.message);
        }
      } catch (notifyError) {
        console.error('❌ 发送最终选派确认通知异常:', notifyError);
        console.error('错误堆栈:', notifyError.stack);
        // 不影响选派确认的主流程
      }

      // 自动生成执裁记录
      await this.generateRefereeRecords(applicationsResult.data, match, schedule, now);

      return {
        code: 0,
        message: `成功确认${applicationsResult.data.length}个选派`,
        data: {
          confirmedCount: applicationsResult.data.length,
          sessionId,
          confirmTime: now
        }
      };
      
    } catch (error) {
      console.error('完成选派失败:', error);
      return {
        code: -1,
        message: '完成选派失败'
      };
    }
  },

  /**
   * 自动生成执裁记录
   * @param {Array} applications - 确认的申请列表
   * @param {Object} match - 比赛信息
   * @param {Object} schedule - 日程信息
   * @param {Date} confirmTime - 确认时间
   */
  async generateRefereeRecords(applications, match, schedule, confirmTime) {
    try {
      console.log('=== 开始自动生成执裁记录 ===');
      console.log('申请数量:', applications.length);
      console.log('比赛信息:', { id: match._id, title: match.title, level: match.level });
      console.log('日程信息:', { date: schedule.date, venue: schedule.venue, slots: schedule.time_slots?.length });
      console.log('确认时间:', confirmTime);
      
      // 获取用户服务，用于获取用户详细信息
      const userService = uniCloud.importObject('user-service');
      
      // 获取执裁记录服务的数据库集合
      const recordsCollection = db.collection('match_referee_records');
      
      let successCount = 0;
      let errorCount = 0;
      
      // 为每个确认的申请生成执裁记录
      for (const app of applications) {
        try {
          console.log(`\n--- 处理申请 ${app._id} ---`);
          console.log('用户ID:', app.user_id, '职位:', app.position, '时段ID:', app.slot_id);
          
          // 获取裁判员详细信息
          const userResult = await db.collection('users').doc(app.user_id).get();
          let refereeName = '未知';
          
          if (userResult.data && userResult.data.length > 0) {
            const userData = userResult.data[0];
            refereeName = userData.nickname || userData.username || userData.realname || userData.name || '未知';
            console.log('裁判员姓名:', refereeName);
          } else {
            console.warn('未找到用户信息:', app.user_id);
          }
         
          // 找到对应的时段信息
          const targetSlot = schedule.time_slots?.find(slot => slot.slot_id === app.slot_id);
          console.log('时段信息:', targetSlot ? 
            { slotId: targetSlot.slot_id, startTime: targetSlot.start_time, endTime: targetSlot.end_time, homeTeam: targetSlot.home_team, awayTeam: targetSlot.away_team } : 
            '未找到时段');
          
          // 检查监督员信息
          const hasSupervisor = module.exports.checkHasSupervisor(applications, app.slot_id);
          const supervisorId = module.exports.getSupervisorId(applications, app.slot_id);
          console.log('监督员检查结果:', { 
            slotId: app.slot_id, 
            hasSupervisor, 
            supervisorId,
            applicationsCount: applications.length 
          });
          
          // 打印该时段的所有申请详情
          const slotApplications = applications.filter(a => a.slot_id === app.slot_id);
          console.log(`时段 ${app.slot_id} 的所有申请:`, slotApplications.map(a => ({
            userId: a.user_id,
            position: a.position,
            status: a.status
          })));
          
          // 构建执裁记录数据
          const recordData = {
            match_id: match._id,
            referee_id: app.user_id,
            referee_name: refereeName,
            position: module.exports.convertPositionToStandard(app.position),
            match_title: match.title,
            match_level: match.level || '未知',
            match_date: module.exports.constructMatchDate(schedule.date, targetSlot?.start_time),
            match_venue: match.location || '未知',
            home_team: targetSlot ? (targetSlot.home_team || '主队') : '主队',
            away_team: targetSlot ? (targetSlot.away_team || '客队') : '客队',
            attendance_status: '正常出勤',
            has_supervisor: hasSupervisor,
            supervisor_id: supervisorId,
            record_status: '待确认',
            create_time: confirmTime,
            update_time: confirmTime,
            // 额外信息，用于追溯
            source_application_id: app._id,
            source_slot_id: app.slot_id,
            source_schedule_id: app.schedule_id
          };
          
          console.log('执裁记录数据:', JSON.stringify(recordData, null, 2));
          
          // 插入执裁记录
          const insertResult = await recordsCollection.add(recordData);
          console.log(`✅ 为用户 ${app.user_id} 生成执裁记录成功，记录ID: ${insertResult.id}`);
          successCount++;
          
        } catch (recordError) {
          console.error(`❌ 为用户 ${app.user_id} 生成执裁记录失败:`, recordError);
          console.error('错误堆栈:', recordError.stack);
          errorCount++;
          // 继续处理其他记录，不中断整个流程
        }
      }
      
      console.log('=== 执裁记录生成完成 ===');
      console.log(`成功生成: ${successCount} 条，失败: ${errorCount} 条`);
      
    } catch (error) {
      console.error('❌ 生成执裁记录失败:', error);
      console.error('错误堆栈:', error.stack);
      // 不抛出错误，避免影响选派确认的主流程
    }
  },

  /**
   * 转换职位名称为标准格式
   */
  convertPositionToStandard(position) {
    const positionMap = {
      '主裁判': '主裁判',
      '助理裁判': '助理裁判',
      '边裁判': '助理裁判', // 统一转换为助理裁判
      '第四官员': '第四官员',
      '裁判监督': '裁判监督'
    };
    return positionMap[position] || position;
  },

  /**
   * 检查该时段是否有监督员
   */
  checkHasSupervisor(applications, slotId) {
    return applications.some(app => 
      app.slot_id === slotId && 
      (app.position === '裁判监督' || app.position === 'referee_supervisor')
    );
  },

  /**
   * 获取监督员ID
   */
  getSupervisorId(applications, slotId) {
    const supervisor = applications.find(app => 
      app.slot_id === slotId && 
      (app.position === '裁判监督' || app.position === 'referee_supervisor')
    );
    return supervisor ? supervisor.user_id : null;
  },

  /**
   * 获取轮次选派汇总（多个时段）
   * @param {Object} params - 参数对象
   * @param {Array} params.sessionIds - 时段ID数组
   * @returns {Object} 返回轮次选派汇总数据
   */
  async getRoundSelectionSummary(params) {
    console.log('=== getRoundSelectionSummary 开始执行 ===');
    console.log('传入参数:', JSON.stringify(params, null, 2));
    
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      console.log('获取到的token:', token ? 'token存在' : 'token不存在');
      
      if (!token) {
        console.log('getRoundSelectionSummary: token验证失败');
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      console.log('token验证结果:', JSON.stringify(verifyResult, null, 2));
      
      if (verifyResult.code !== 0) {
        console.log('getRoundSelectionSummary: 身份验证失败');
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      console.log('验证成功，用户ID:', userId);
      
      const { sessionIds, viewerRole, viewerId, onlyConfirmed, onlySelected } = params;

      if (!sessionIds || !Array.isArray(sessionIds) || sessionIds.length === 0) {
        console.log('getRoundSelectionSummary: sessionIds验证失败');
        console.log('sessionIds:', sessionIds);
        return {
          code: -1,
          message: '时段ID数组不能为空'
        };
      }

      console.log('=== 开始查询多个时段的申请 ===');
      console.log('时段IDs:', sessionIds);
      console.log('查看者角色:', viewerRole);
      console.log('查看者ID:', viewerId);
      console.log('只查看已确认:', onlyConfirmed);
      console.log('只查看已选派:', onlySelected);
      
      // 获取所有时段的申请
      const allMatches = [];
      let totalSelected = 0;
      let seriesTitle = '';

      for (const sessionId of sessionIds) {
        console.log(`\n=== 处理时段 ${sessionId} ===`);
        
        // 获取该时段所有申请
        const applicationsResult = await db.collection('match_applications')
          .where({
            slot_id: sessionId
          })
          .get();

        console.log(`时段 ${sessionId} 找到 ${applicationsResult.data.length} 个申请`);
        if (applicationsResult.data.length > 0) {
          console.log(`时段 ${sessionId} 申请状态分布:`, 
            applicationsResult.data.reduce((acc, app) => {
              acc[app.status] = (acc[app.status] || 0) + 1;
              return acc;
            }, {})
          );
        }

        // 根据查看者角色和参数决定过滤逻辑
        let validApplications = [];
        
        if (onlyConfirmed) {
          // 只查看已确认的选派（比赛管理员查看选派表）
          validApplications = applicationsResult.data.filter(app => 
            app.status === 'confirmed'
          );
          console.log(`时段 ${sessionId} 过滤后的confirmed申请: ${validApplications.length}个`);
        } else if (onlySelected) {
          // 只查看已选派但未确认的申请（生成选派表）
          validApplications = applicationsResult.data.filter(app => 
            app.status === 'selected'
          );
          console.log(`时段 ${sessionId} 过滤后的selected申请: ${validApplications.length}个`);
        } else if (viewerRole === 'referee') {
          // 裁判查看：显示所有已选派的申请
          validApplications = applicationsResult.data.filter(app => 
            app.status === 'confirmed'
          );
          console.log(`时段 ${sessionId} 裁判查看的confirmed申请: ${validApplications.length}个`);
        } else {
          // 管理员查看：原有逻辑（生成轮次选派表）
          const selectedApplications = applicationsResult.data.filter(app => app.status === 'selected');
          if (selectedApplications.length === 0) {
            console.log(`时段 ${sessionId} 没有selected状态的申请，跳过`);
            continue;
          }

          const confirmedApplications = applicationsResult.data.filter(app => app.status === 'confirmed');
          if (confirmedApplications.length > 0) {
            console.log(`时段 ${sessionId} 已有confirmed状态的申请，跳过`);
            continue;
          }
          
          validApplications = selectedApplications;
          console.log(`时段 ${sessionId} 管理员查看的selected申请: ${validApplications.length}个`);
        }

        if (validApplications.length === 0) {
          console.log(`时段 ${sessionId} 没有有效的申请，跳过`);
          continue;
        }

        console.log(`时段 ${sessionId} 符合条件：${validApplications.length}个有效申请`);

        // 权限验证（只需要验证第一个时段的权限）
        if (allMatches.length === 0) {
          console.log(`\n=== 开始权限验证（基于时段 ${sessionId}）===`);
          
          // 通过时段ID获取日程信息进行权限验证
          const scheduleResult = await db.collection('match_schedules')
            .where({
              'time_slots.slot_id': sessionId
            })
            .get();

          console.log(`时段 ${sessionId} 对应的日程查询结果: ${scheduleResult.data.length}条`);
          
          if (!scheduleResult.data.length) {
            console.log(`时段 ${sessionId} 对应的日程不存在`);
            return {
              code: -1,
              message: '时段不存在'
            };
          }

          const schedule = scheduleResult.data[0];
          console.log(`找到日程，比赛ID: ${schedule.match_id}`);
          
          const matchResult = await db.collection('matches')
            .doc(schedule.match_id)
            .get();

          console.log(`比赛查询结果: ${matchResult.data.length}条`);
          
          if (!matchResult.data.length) {
            console.log(`比赛 ${schedule.match_id} 不存在`);
            return {
              code: -1,
              message: '比赛不存在'
            };
          }

          const match = matchResult.data[0];
          console.log(`比赛信息: ${match.title}, 发布者: ${match.publisher_id}`);
          
          // 根据查看者角色和参数验证权限
          if (viewerRole === 'referee') {
            // 裁判查看：验证是否参与了该时段的申请（无论是否已确认都可以查看）
            console.log(`权限验证(referee): 查找用户${viewerId}的申请`);
            const userApplication = validApplications.find(app => app.user_id === viewerId);
            if (!userApplication) {
              console.log('权限验证失败: 用户没有参与该时段的申请');
              console.log('有效申请的用户ID:', validApplications.map(app => app.user_id));
              return {
                code: -1,
                message: '您没有参与该时段的申请，无法查看选派表'
              };
            }
            console.log('权限验证成功: 找到用户申请');
          } else if (onlyConfirmed) {
            // 管理员查看已确认选派表：验证是否为比赛发布者
            console.log(`权限验证(onlyConfirmed): 当前用户${userId} vs 发布者${match.publisher_id}`);
            if (match.publisher_id !== userId) {
              console.log('权限验证失败: 不是比赛发布者');
              return {
                code: -1,
                message: '只有比赛发布者才能查看选派表'
              };
            }
          } else if (onlySelected) {
            // 管理员查看待确认选派表：验证是否为比赛发布者
            console.log(`权限验证(onlySelected): 当前用户${userId} vs 发布者${match.publisher_id}`);
            if (match.publisher_id !== userId) {
              console.log('权限验证失败: 不是比赛发布者');
              return {
                code: -1,
                message: '只有比赛发布者才能查看选派表'
              };
            }
          } else {
            // 其他情况（管理员查看）：验证是否为比赛发布者
            console.log(`权限验证(admin): 当前用户${userId} vs 发布者${match.publisher_id}`);
            if (match.publisher_id !== userId) {
              console.log('权限验证失败: 不是比赛发布者');
              return {
                code: -1,
                message: '只有比赛发布者才能查看选派汇总'
              };
            }
          }

          seriesTitle = match.title || '系列赛';
          console.log(`权限验证通过，系列赛名称: ${seriesTitle}`);
        }

        // 获取时段信息
        console.log(`\n=== 获取时段 ${sessionId} 的详细信息 ===`);
        const scheduleResult = await db.collection('match_schedules')
          .where({
            'time_slots.slot_id': sessionId
          })
          .get();

        if (!scheduleResult.data.length) {
          console.log(`时段 ${sessionId} 对应的日程不存在，跳过`);
          continue;
        }

        const schedule = scheduleResult.data[0];
        const targetSlot = schedule.time_slots.find(slot => slot.slot_id === sessionId);
        
        if (!targetSlot) {
          console.log(`时段 ${sessionId} 信息不存在，跳过`);
          continue;
        }

        console.log(`时段 ${sessionId} 信息:`, {
          date: schedule.date,
          time: `${targetSlot.start_time}-${targetSlot.end_time}`,
          venue: targetSlot.venue,
          teams: `${targetSlot.home_team} vs ${targetSlot.away_team}`
        });

        // 按岗位分组用户
        const positions = {
          main_referee: null,
          assistant_referee: null,
          fourth_official: null,
          referee_supervisor: null
        };

        // 使用已经过滤的有效申请来分配岗位
        console.log(`\n=== 分配岗位（时段 ${sessionId}）===`);
        for (const app of validApplications) {
          const position = app.position || 'main_referee';
          console.log(`处理申请: 用户${app.user_id}, 岗位${position}`);
          
          // 获取用户认证信息
          const credentialInfo = await module.exports.getUserCredentialInfo(app.user_id, null);
          
          // 获取申请时填写的联系电话（优先从申请记录中获取）
          const contactPhone = app.contact_phone || app.contact_info || '';
          
          const userData = {
            user_id: app.user_id,
            user_name: credentialInfo.real_name || '匿名用户',
            phone: contactPhone
          };

          // 只取每个岗位的第一个人
          if (!positions[position]) {
            positions[position] = userData;
            console.log(`岗位${position}分配给: ${userData.user_name} (${userData.phone})`);
          } else {
            console.log(`岗位${position}已有人员，跳过${userData.user_name}`);
          }
        }

        console.log(`时段 ${sessionId} 最终岗位分配:`, positions);

        // 构建比赛记录
        const matchRecord = {
          date: schedule.date,
          time_range: `${targetSlot.start_time}-${targetSlot.end_time}`,
          venue: targetSlot.venue || schedule.venue || '1号场',
          home_team: targetSlot.home_team || '主队',
          away_team: targetSlot.away_team || '客队',
          main_referee: positions.main_referee ? positions.main_referee.user_name : '-',
          main_referee_phone: positions.main_referee ? positions.main_referee.phone : '',
          assistant_referee: positions.assistant_referee ? positions.assistant_referee.user_name : '-',
          assistant_referee_phone: positions.assistant_referee ? positions.assistant_referee.phone : '',
          fourth_official: positions.fourth_official ? positions.fourth_official.user_name : '-',
          fourth_official_phone: positions.fourth_official ? positions.fourth_official.phone : '',
          referee_supervisor: positions.referee_supervisor ? positions.referee_supervisor.user_name : '-',
          referee_supervisor_phone: positions.referee_supervisor ? positions.referee_supervisor.phone : ''
        };

        console.log(`时段 ${sessionId} 构建的比赛记录:`, matchRecord);

        allMatches.push(matchRecord);
        totalSelected += validApplications.length;
      }

      console.log(`\n=== 所有时段处理完成 ===`);
      console.log(`总比赛场次: ${allMatches.length}`);
      console.log(`总选派人次: ${totalSelected}`);

      if (allMatches.length === 0) {
        console.log('没有找到符合条件的比赛时段');
        return {
          code: -1,
          message: '没有找到符合条件的比赛时段'
        };
      }

      // 按日期和时间排序
      allMatches.sort((a, b) => {
        if (a.date !== b.date) {
          return new Date(a.date) - new Date(b.date);
        }
        return a.time_range.localeCompare(b.time_range);
      });

      // 构建汇总数据
      console.log('\n=== 构建汇总数据 ===');
      const summaryData = {
        series_title: seriesTitle,
        total_matches: allMatches.length,
        total_selected: totalSelected,
        session_ids: sessionIds,
        matches: allMatches
      };

      console.log('汇总数据构建完成:', {
        series_title: summaryData.series_title,
        total_matches: summaryData.total_matches,
        total_selected: summaryData.total_selected,
        session_ids: summaryData.session_ids,
        matches_count: summaryData.matches.length
      });

      return {
        code: 0,
        message: '获取轮次选派汇总成功',
        data: summaryData
      };
      
    } catch (error) {
      console.error('=== getRoundSelectionSummary 异常 ===');
      console.error('异常详情:', error);
      console.error('异常堆栈:', error.stack);
      return {
        code: -1,
        message: '获取轮次选派汇总失败: ' + error.message
      };
    }
  },

  /**
   * 完成轮次选派（批量确认多个时段）
   * @param {Object} params - 参数对象
   * @param {Array} params.sessionIds - 时段ID数组
   * @returns {Object} 返回操作结果
   */
  async completeRoundSelection(params) {
    console.log('completeRoundSelection 开始执行，参数:', params);
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { sessionIds } = params;

      if (!sessionIds || !Array.isArray(sessionIds) || sessionIds.length === 0) {
        return {
          code: -1,
          message: '时段ID数组不能为空'
        };
      }

      console.log('completeRoundSelection: 开始批量确认，时段IDs:', sessionIds);

      let totalConfirmed = 0;
      const results = [];

      // 批量处理每个时段
      for (const sessionId of sessionIds) {
        try {
          // 获取该时段所有selected状态的申请
          const applicationsResult = await db.collection('match_applications')
            .where({
              slot_id: sessionId,
              status: 'selected'
            })
            .get();

          if (applicationsResult.data.length === 0) {
            console.log(`时段 ${sessionId} 没有selected状态的申请，跳过`);
            continue;
          }

          // 权限验证
          const firstApp = applicationsResult.data[0];
          const scheduleResult = await db.collection('match_schedules')
            .doc(firstApp.schedule_id)
            .get();

          if (!scheduleResult.data.length) {
            console.log(`时段 ${sessionId} 对应的日程不存在，跳过`);
            continue;
          }

          const schedule = scheduleResult.data[0];
          const matchResult = await db.collection('matches')
            .doc(schedule.match_id)
            .get();

          if (!matchResult.data.length) {
            console.log(`时段 ${sessionId} 对应的比赛不存在，跳过`);
            continue;
          }

          const match = matchResult.data[0];
          
          if (match.publisher_id !== userId) {
            console.log(`时段 ${sessionId} 权限验证失败，跳过`);
            continue;
          }

          // 批量更新该时段的申请状态
          const updatePromises = applicationsResult.data.map(app => {
            return db.collection('match_applications')
              .doc(app._id)
              .update({
                status: 'confirmed',
                review_time: new Date(),
                review_note: '轮次选派确认'
              });
          });

          await Promise.all(updatePromises);
          
          // 发送最终选派确认通知给该时段的所有确认申请人
          try {
            console.log(`开始发送时段 ${sessionId} 的最终选派确认通知...`);
            const notificationService = uniCloud.importObject('notification-service');
            
            // 找到对应的时段信息
            const targetSlot = schedule.time_slots?.find(slot => slot.slot_id === sessionId);
            const matchTimeSlot = targetSlot ? `${targetSlot.start_time}-${targetSlot.end_time}` : '时段未定';
            const matchTeams = targetSlot ? `${targetSlot.home_team || '主队'} vs ${targetSlot.away_team || '客队'}` : '对阵待定';
            
            // 批量发送通知
            const userIds = applicationsResult.data.map(app => app.user_id);
            console.log(`准备发送通知给时段 ${sessionId} 的用户:`, userIds);
            
            const notificationParams = {
              userIds: userIds,
              type: 'match_review',
              title: '比赛选派最终确认',
              content: `恭喜！您的比赛申请已最终确认选派。比赛：${match.title}，时段：${matchTimeSlot}，对阵：${matchTeams}。请按时参加比赛，执裁记录已自动生成。`,
              relatedId: match._id,
              senderId: userId,
              extraData: {
                jump_type: 'selection_table',
                jump_url: `/packageMy/my/schedule-viewer?sessionId=${sessionId}&role=referee&viewMode=confirmed`,
                match_id: match._id,
                session_id: sessionId,
                match_time_slot: matchTimeSlot,
                review_result: 'confirmed',
                // 添加选派表相关数据
                selection_data: {
                  session_ids: [sessionId],
                  viewer_role: 'referee',
                  only_confirmed: true
                }
              }
            };
            
            console.log(`时段 ${sessionId} 通知参数:`, JSON.stringify(notificationParams, null, 2));
            
            const notifyResult = await notificationService.batchSendNotification(notificationParams);
            console.log(`时段 ${sessionId} 通知发送结果:`, notifyResult);
            
            if (notifyResult.code === 0) {
              console.log(`✅ 时段 ${sessionId} 最终选派确认通知发送成功，共 ${userIds.length} 名用户`);
            } else {
              console.error(`❌ 时段 ${sessionId} 通知发送失败:`, notifyResult.message);
            }
          } catch (notifyError) {
            console.error(`❌ 时段 ${sessionId} 发送最终选派确认通知异常:`, notifyError);
            console.error('错误堆栈:', notifyError.stack);
            // 不影响选派确认的主流程
          }
          
          // 生成执裁记录
          const now = new Date();
          console.log(`时段 ${sessionId} 开始生成执裁记录，申请数量: ${applicationsResult.data.length}`);
          console.log(`时段 ${sessionId} 申请详情:`, applicationsResult.data.map(app => ({
            userId: app.user_id,
            position: app.position,
            status: app.status,
            slotId: app.slot_id
          })));
          
          await module.exports.generateRefereeRecords(applicationsResult.data, match, schedule, now);
          console.log(`时段 ${sessionId} 执裁记录生成完成`);
          
          totalConfirmed += applicationsResult.data.length;
          results.push({
            sessionId: sessionId,
            confirmed: applicationsResult.data.length
          });

          console.log(`时段 ${sessionId} 确认了 ${applicationsResult.data.length} 个申请并生成执裁记录`);

        } catch (sessionError) {
          console.error(`处理时段 ${sessionId} 时出错:`, sessionError);
          results.push({
            sessionId: sessionId,
            error: sessionError.message
          });
        }
      }

      console.log('completeRoundSelection: 批量确认完成，总计确认:', totalConfirmed);

      return {
        code: 0,
        message: `轮次选派完成，共确认 ${totalConfirmed} 人次`,
        data: {
          total_confirmed: totalConfirmed,
          results: results
        }
      };

    } catch (error) {
      console.error('完成轮次选派失败:', error);
      console.error('错误详情:', error.stack);
      return {
        code: -1,
        message: '完成轮次选派失败: ' + error.message
      };
    }
  },

  /**
   * 获取选派汇总信息
   */
  async getSelectionSummary(params) {
    console.log('getSelectionSummary 开始执行，参数:', params);
    try {
      // 使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        console.log('getSelectionSummary: token验证失败');
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        console.log('getSelectionSummary: 用户验证失败', verifyResult);
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;
      const { sessionId } = params;

      console.log('getSelectionSummary: 用户ID:', userId, '时段ID:', sessionId);

      if (!sessionId) {
        console.log('getSelectionSummary: 时段ID为空');
        return {
          code: -1,
          message: '时段ID不能为空'
        };
      }

      // 获取该时段所有selected状态的申请
      console.log('getSelectionSummary: 查询申请，条件:', { slot_id: sessionId, status: 'selected' });
      const applicationsResult = await db.collection('match_applications')
        .where({
          slot_id: sessionId,
          status: 'selected'
        })
        .get();

      console.log('getSelectionSummary: 查询到的申请数量:', applicationsResult.data.length);
      if (applicationsResult.data.length === 0) {
        console.log('getSelectionSummary: 没有待确认的选派');
        return {
          code: -1,
          message: '没有待确认的选派'
        };
      }

      // 验证权限
      console.log('getSelectionSummary: 开始权限验证');
      const firstApp = applicationsResult.data[0];
      console.log('getSelectionSummary: 第一个申请信息:', firstApp);
      
      const scheduleResult = await db.collection('match_schedules')
        .doc(firstApp.schedule_id)
        .get();

      console.log('getSelectionSummary: 日程查询结果:', scheduleResult.data.length);
      if (!scheduleResult.data.length) {
        console.log('getSelectionSummary: 时段不存在');
        return {
          code: -1,
          message: '时段不存在'
        };
      }

      const schedule = scheduleResult.data[0];
      console.log('getSelectionSummary: 日程信息:', schedule);
      
      const matchResult = await db.collection('matches')
        .doc(schedule.match_id)
        .get();

      console.log('getSelectionSummary: 比赛查询结果:', matchResult.data.length);
      if (!matchResult.data.length) {
        console.log('getSelectionSummary: 比赛不存在');
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      const match = matchResult.data[0];
      console.log('getSelectionSummary: 比赛信息:', match);
      console.log('getSelectionSummary: 权限验证 - 比赛发布者:', match.publisher_id, '当前用户:', userId);
      
      if (match.publisher_id !== userId) {
        console.log('getSelectionSummary: 权限验证失败');
        return {
          code: -1,
          message: '只有比赛发布者才能查看选派汇总'
        };
      }

      // 获取时段信息
      console.log('getSelectionSummary: 查找时段信息，sessionId:', sessionId);
      console.log('getSelectionSummary: 可用时段:', schedule.time_slots);
      const targetSlot = schedule.time_slots.find(slot => slot.slot_id === sessionId);
      console.log('getSelectionSummary: 目标时段:', targetSlot);
      
      if (!targetSlot) {
        console.log('getSelectionSummary: 时段信息不存在');
        return {
          code: -1,
          message: '时段信息不存在'
        };
      }

      // 获取用户信息并按岗位分组
      console.log('getSelectionSummary: 开始处理用户信息');
      const positionGroups = {};
      for (const app of applicationsResult.data) {
        console.log('getSelectionSummary: 处理申请:', app);
        const position = app.position || 'main_referee';
        
        if (!positionGroups[position]) {
          positionGroups[position] = [];
        }

        try {
          // 获取用户认证信息
          console.log('getSelectionSummary: 获取用户认证信息，用户ID:', app.user_id);
          const credentialInfo = await module.exports.getUserCredentialInfo(app.user_id, null);
          console.log('getSelectionSummary: 用户认证信息:', credentialInfo);
          
          positionGroups[position].push({
            user_id: app.user_id,
            user_name: credentialInfo.real_name || '匿名用户',
            identity: credentialInfo.identity,
            level: credentialInfo.level,
            organization: credentialInfo.register_organization,
            application_id: app._id
          });
        } catch (error) {
          console.error('getSelectionSummary: 获取用户认证信息失败:', error);
          positionGroups[position].push({
            user_id: app.user_id,
            user_name: '匿名用户',
            identity: '普通用户',
            level: '',
            organization: '',
            application_id: app._id
          });
        }
      }

      // 构建汇总数据
      console.log('getSelectionSummary: 构建汇总数据');
      const summaryData = {
        match_title: match.title || '比赛',
        match_date: schedule.date,
        session_time: `${targetSlot.start_time}-${targetSlot.end_time}`,
        home_team: targetSlot.home_team || '主队',
        away_team: targetSlot.away_team || '客队',
        venue: targetSlot.venue || schedule.venue || '场地待定',
        positions: positionGroups,
        total_selected: applicationsResult.data.length,
        session_id: sessionId
      };

      console.log('getSelectionSummary: 汇总数据构建完成:', summaryData);
      return {
        code: 0,
        message: '获取选派汇总成功',
        data: summaryData
      };
      
    } catch (error) {
      console.error('获取选派汇总失败:', error);
      console.error('错误详情:', error.stack);
      return {
        code: -1,
        message: '获取选派汇总失败: ' + error.message
      };
    }
  },

  /**
   * 计算年龄（根据身份证号）
   */
  calculateAge(idCard) {
    if (!idCard || idCard.length < 14) return 0;
    
    try {
      const birthYear = idCard.length === 18 ? 
        parseInt(idCard.substring(6, 10)) : 
        parseInt('19' + idCard.substring(6, 8));
      
      const currentYear = new Date().getFullYear();
      return currentYear - birthYear;
    } catch (error) {
      return 0;
    }
  },

  /**
   * 获取用户认证信息
   */
  async getUserCredentialInfo(userId, userRole) {
    try {
      console.log('获取用户认证信息，用户ID:', userId, '角色:', userRole);
      
      let credentialInfo = {
        real_name: '',
        phone: '',
        gender: '',
        age: '',
        level: '',
        identity: '普通用户',
        register_organization: '',
        register_date: ''
      };

      // 先尝试查询裁判员认证
      console.log('查询裁判员认证信息');
      const refereeResult = await db.collection('referee_credentials')
        .where({ 
          user_id: userId,
          status: 'approved' 
        })
        .orderBy('create_time', 'desc')
        .limit(1)
        .get();

      console.log('裁判员认证查询结果:', refereeResult.data.length);
      if (refereeResult.data.length > 0) {
        const referee = refereeResult.data[0];
        console.log('裁判员认证信息:', referee);
        credentialInfo = {
          real_name: referee.real_name || '',
          phone: '', // 认证表中没有手机号，后续从用户表获取
          gender: referee.gender || '',
          age: referee.age || '',
          level: module.exports.formatRefereeLevel(referee.level),
          identity: '裁判员',
          register_organization: referee.register_organization || '',
          register_date: referee.register_date || ''
        };
      } else {
        // 如果没有裁判员认证，查询裁判监督认证
        console.log('查询裁判监督认证信息');
        const supervisorResult = await db.collection('supervisor_credentials')
          .where({ 
            user_id: userId,
            status: 'approved' 
          })
          .orderBy('create_time', 'desc')
          .limit(1)
          .get();

        console.log('裁判监督认证查询结果:', supervisorResult.data.length);
        if (supervisorResult.data.length > 0) {
          const supervisor = supervisorResult.data[0];
          console.log('裁判监督认证信息:', supervisor);
          credentialInfo = {
            real_name: supervisor.real_name || '',
            phone: '', // 认证表中没有手机号，后续从用户表获取
            gender: supervisor.gender || '',
            age: supervisor.age || '',
            level: '', // 裁判监督没有等级
            identity: '裁判监督',
            register_organization: supervisor.register_organization || '',
            register_date: supervisor.register_date || ''
          };
        } else {
          console.log('用户没有任何认证信息');
        }
      }

      console.log('最终认证信息:', credentialInfo);
      return credentialInfo;
    } catch (error) {
      console.error('获取用户认证信息失败:', error);
      return {
        real_name: '',
        phone: '',
        gender: '',
        age: '',
        level: '',
        identity: '普通用户',
        register_organization: '',
        register_date: ''
      };
    }
  },

  /**
   * 格式化裁判等级
   */
  formatRefereeLevel(level) {
    const levelMap = {
      1: '三级裁判员',
      2: '二级裁判员',
      3: '一级裁判员',
      4: '预备国家级裁判员',
      5: '国家级裁判员',
      6: '国际级裁判员'
    };
    return levelMap[level] || '';
  },

  /**
   * 检查时间冲突
   */
  async checkTimeConflicts(userId, currentSessionId) {
    try {
      // 获取当前时段信息
      const currentSessionResult = await db.collection('match_schedules')
        .doc(currentSessionId)
        .get();

      if (!currentSessionResult.data.length) {
        return [];
      }

      const currentSession = currentSessionResult.data[0];
      const currentDate = currentSession.date;
      const currentStartTime = currentSession.start_time;
      const currentEndTime = currentSession.end_time;

      // 查找用户在同一天的其他申请
      const applicationsResult = await db.collection('match_applications')
        .where({
          user_id: userId,
          status: db.command.in(['pending', 'approved'])
        })
        .get();

      const conflicts = [];
      for (const app of applicationsResult.data) {
        if (app.slot_id === currentSessionId) {
          continue; // 跳过当前申请
        }

        // 获取申请时段信息
        const sessionResult = await db.collection('match_schedules')
          .doc(app.slot_id)
          .get();

        if (sessionResult.data.length > 0) {
          const session = sessionResult.data[0];
          
          // 检查是否是同一天
          if (session.date === currentDate) {
            // 检查时间是否重叠
            if (module.exports.isTimeOverlap(currentStartTime, currentEndTime, session.start_time, session.end_time)) {
              conflicts.push({
                session_id: app.slot_id,
                time_range: `${session.start_time}-${session.end_time}`,
                event_name: session.event_name || '比赛'
              });
            }
          }
        }
      }

      return conflicts;
    } catch (error) {
      console.error('检查时间冲突失败:', error);
      return [];
    }
  },

  /**
   * 判断时间是否重叠
   */
  isTimeOverlap(start1, end1, start2, end2) {
    // 将时间转换为分钟数进行比较
    const timeToMinutes = (timeStr) => {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    };

    const start1Minutes = timeToMinutes(start1);
    const end1Minutes = timeToMinutes(end1);
    const start2Minutes = timeToMinutes(start2);
    const end2Minutes = timeToMinutes(end2);

    return start1Minutes < end2Minutes && start2Minutes < end1Minutes;
  },

  /**
   * 构造比赛日期
   */
  constructMatchDate(date, startTime) {
    // 如果是字符串日期格式 (YYYY-MM-DD)
    if (typeof date === 'string' && date.includes('-')) {
      const dateStr = date.split('T')[0]; // 确保只取日期部分
      const timeStr = startTime || '00:00';
      return new Date(`${dateStr}T${timeStr}:00.000Z`);
    }
    
    // 如果是Date对象
    if (date instanceof Date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const timeStr = startTime || '00:00';
      return new Date(`${year}-${month}-${day}T${timeStr}:00.000Z`);
    }
    
    // 默认返回当前时间
    return new Date();
  },

  /**
   * 【新增】验证申请取消权限
   * @param {Object} application 申请对象
   * @returns {Object} 验证结果
   */
  validateCancelPermission(application) {
    if (!application) {
      return {
        allowed: false,
        code: 404,
        message: '申请不存在',
        reason: 'application_not_found'
      };
    }

    switch (application.status) {
      case 'cancelled':
        return {
          allowed: false,
          code: 400,
          message: '申请已经取消',
          reason: 'already_cancelled'
        };

      case 'selected':
        return {
          allowed: false,
          code: 400,
          message: '申请已被选派，无法取消。如有疑问请联系比赛组织者。',
          reason: 'application_selected'
        };

      case 'confirmed':
        return {
          allowed: false,
          code: 400,
          message: '申请已完成最终选派确认，无法取消。如有紧急情况请联系比赛组织者。',
          reason: 'application_confirmed'
        };

      case 'rejected':
        return {
          allowed: false,
          code: 400,
          message: '申请已被拒绝，无法取消。',
          reason: 'application_rejected'
        };

      case 'pending':
        return {
          allowed: true,
          code: 200,
          message: '允许取消',
          reason: 'cancellable'
        };

      default:
        return {
          allowed: false,
          code: 400,
          message: `未知的申请状态: ${application.status}，无法取消。`,
          reason: 'unknown_status'
        };
    }
  },

  /**
   * 【新增】验证状态流转权限
   * @param {string} fromStatus 当前状态
   * @param {string} toStatus 目标状态
   * @returns {Object} 验证结果
   */
  validateStatusTransition(fromStatus, toStatus) {
    const validTransitions = {
      'pending': ['selected', 'rejected'],
      'selected': ['pending', 'confirmed'],  // selected可以撤回到pending或确认为confirmed
      'confirmed': [],  // confirmed是最终状态，不可变更
      'rejected': [],   // rejected是最终状态，不可变更
      'cancelled': []   // cancelled是最终状态，不可变更
    };

    if (!validTransitions[fromStatus]) {
      return {
        allowed: false,
        code: 400,
        message: `未知的起始状态: ${fromStatus}`,
        reason: 'unknown_from_status'
      };
    }

    if (!validTransitions[fromStatus].includes(toStatus)) {
      return {
        allowed: false,
        code: 400,
        message: `无法从 ${fromStatus} 状态变更为 ${toStatus} 状态`,
        reason: 'invalid_transition'
      };
    }

    return {
      allowed: true,
      code: 200,
      message: '状态流转有效',
      reason: 'valid_transition'
    };
  },

  /**
   * 【新增】记录操作日志
   * @param {Object} logData 日志数据
   */
  async recordOperationLog(logData) {
    try {
      await db.collection('operation_logs').add({
        ...logData,
        operation_time: new Date(),
        client_info: this.clientInfo || {}
      });
    } catch (error) {
      console.error('记录操作日志失败:', error);
      // 不抛出异常，避免影响主流程
    }
  },

  /**
   * 【新增】初始化操作日志表
   */
  async initOperationLogsTable() {
    try {
      // 简化初始化逻辑，直接尝试创建第一条记录来初始化表
      console.log('初始化操作日志表...');
      
      // 尝试插入一条初始化记录，如果表不存在会自动创建
      await db.collection('operation_logs').add({
        operation_type: 'system_init',
        operator_id: 'system',
        target_type: 'initialization',
        target_id: 'operation_logs_table',
        operation_data: {
          message: '操作日志表初始化'
        },
        operation_time: new Date(),
        client_info: this.clientInfo || {}
      });
      
      console.log('操作日志表初始化完成');
    } catch (error) {
      // 如果表已经存在，插入可能会成功，如果是其他错误则记录但不影响主流程
      console.log('操作日志表初始化完成（表可能已存在）');
    }
  },

  /**
   * 【新增】获取权限验证摘要报告
   * @param {string} userId 用户ID
   * @param {Array} applicationIds 申请ID数组
   */
  async getPermissionSummary(userId, applicationIds) {
    try {
      if (!applicationIds || applicationIds.length === 0) {
        return {
          code: 0,
          data: {
            total: 0,
            cancellable: 0,
            non_cancellable: 0,
            details: []
          }
        };
      }

      const applications = await db.collection('match_applications')
        .where({
          _id: db.command.in(applicationIds),
          user_id: userId
        })
        .get();

      const summary = {
        total: applications.data.length,
        cancellable: 0,
        non_cancellable: 0,
        details: []
      };

              applications.data.forEach(app => {
          const permission = module.exports.validateCancelPermission(app);
        const detail = {
          application_id: app._id,
          position: app.position,
          status: app.status,
          cancellable: permission.allowed,
          reason: permission.reason,
          message: permission.message
        };

        if (permission.allowed) {
          summary.cancellable++;
        } else {
          summary.non_cancellable++;
        }

        summary.details.push(detail);
      });

      return {
        code: 0,
        data: summary
      };

    } catch (error) {
      console.error('获取权限验证摘要失败:', error);
      return {
        code: -1,
        message: '获取权限摘要失败: ' + error.message
      };
    }
  }
}; 